<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      //模拟请求函数
      function request() {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            resolve("请求信息");
          }, 2000);
        });
      }

      //定时器
      function timeOut(deley) {
        //如果超时则返回出一个错误的promise对象
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            reject("超时");
          }, deley);
        });
      }
      // let restart = 0;
      //让promise.race和定时器赛跑 如果超时再做一些逻辑 restart重新请求五次
      function overTime(fn, deley, restart) {
        //重新请求三次
        // let restart = 0;
        return new Promise((resolve, reject) => {
          //判断看是请求先执行完还是计时器 由此来判断是否超时
          Promise.race([fn(), timeOut(deley)])
            .then((res) => {
              // console.log(res);
              resolve(res);
            })
            .catch((err) => {
              //返回拒绝promise则表明超时
              reject(err);
            });
        }).catch((err) => {
          restart--;
          //失败之后重新请求
          if (restart > 0) {
            console.log(restart);
            return overTime(fn, deley, restart);
          }

          return err;
        });
      }

      overTime(request, 1000, 5)
        .then((res) => {
          console.log(res);
        })
        .catch((reson) => {
          console.log(reson);
        });

      //promise.race

      Promise.myRace = function (promiseArr) {
        if (Array.isArray(promiseArr)) {
          return;
        }

        return new Promise((resolve, reject) => {
          promiseArr.forEach((promise) => {
            promise
              .then((value) => {
                resolve(value);
              })
              .catch((reject) => {
                reject(reject);
              });
          });
        });
      };
    </script>
  </body>
</html>
